package org.dousb.doupicturebackend.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.dousb.doupicturebackend.common.ErrorCode;
import org.dousb.doupicturebackend.config.CosClientConfig;
import org.dousb.doupicturebackend.exception.BusinessException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Cos 对象操作
 */
@Component
public class CosManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象(附带图片信息)
     *
     * @param key  唯一键
     * @param file 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                file);
        //处理图片信息
        PicOperations picOperations = new PicOperations();
        //返回原图信息
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> rules = new ArrayList<>();
        //图片压缩
        String webpKey = FileUtil.mainName(key) + ".webp";
        PicOperations.Rule compressRule = new PicOperations.Rule();
        compressRule.setRule("imageMogr2/format/webp");
        compressRule.setBucket(cosClientConfig.getBucket());
        compressRule.setFileId(webpKey);
        rules.add(compressRule);
        //缩略图处理 只对大于20kb的文件 使用缩略图
        if (file.length() > 1024 * 2) {
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setBucket(cosClientConfig.getBucket());
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail" + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            //缩放规则
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 128, 128));
            rules.add(thumbnailRule);
        }

        //构造处理参数
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     *
     * @param key 唯一键
     * @return
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }


    /**
     * 删除对象
     *
     * @param key 文件key
     * @throws CosClientException
     */
    public void deleteObject(String key) throws CosClientException {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }

    /**
     * 生成预签名URL
     *
     * @param objectUrl
     * @param expireSeconds
     * @return
     */
    public String generatePresignedUrl(String objectUrl, int expireSeconds) {
        // 从URL中解析出Bucket名称和对象键（Key）
        // 示例URL：https://{bucket}.cos.{region}.myqcloud.com/{key}
        URL url;
        try {
            url = new URL(objectUrl);
            String host = url.getHost();
            String bucket = host.split("\\.")[0]; // 提取bucket名称
            String key = url.getPath().substring(1); // 提取对象Key（去除开头的"/"）

            // 生成预签名URL
            Date expiration = new Date(System.currentTimeMillis() + expireSeconds * 1000L);
            URL presignedUrl = cosClient.generatePresignedUrl(bucket, key, expiration);
            return presignedUrl.toString();
        } catch (Exception e) {

            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "生成图片访问链接失败");
        }
    }

}
